/**
 * 性能监控和优化工具
 */

// 性能指标收集
export class PerformanceMonitor {
  constructor() {
    this.metrics = {}
    this.init()
  }

  init() {
    // 页面加载性能
    this.observePageLoad()
    // 资源加载性能
    this.observeResourceLoad()
    // 长任务监控
    this.observeLongTasks()
    // 内存使用监控
    this.observeMemory()
  }

  // 页面加载性能监控
  observePageLoad() {
    window.addEventListener('load', () => {
      if ('performance' in window) {
        const perfData = performance.getEntriesByType('navigation')[0]
        this.metrics.pageLoad = {
          loadTime: perfData.loadEventEnd - perfData.loadEventStart,
          domReady: perfData.domContentLoadedEventEnd - perfData.domContentLoadedEventStart,
          firstPaint: this.getFirstPaint(),
          firstContentfulPaint: this.getFirstContentfulPaint()
        }
        console.log('页面性能指标:', this.metrics.pageLoad)
      }
    })
  }

  // 资源加载性能监控
  observeResourceLoad() {
    if ('PerformanceObserver' in window) {
      const observer = new PerformanceObserver((list) => {
        list.getEntries().forEach((entry) => {
          if (entry.entryType === 'resource') {
            this.metrics.resources = this.metrics.resources || []
            this.metrics.resources.push({
              name: entry.name,
              duration: entry.duration,
              size: entry.transferSize,
              type: entry.initiatorType
            })
          }
        })
      })
      observer.observe({ entryTypes: ['resource'] })
    }
  }

  // 长任务监控
  observeLongTasks() {
    if ('PerformanceObserver' in window) {
      const observer = new PerformanceObserver((list) => {
        list.getEntries().forEach((entry) => {
          if (entry.duration > 50) { // 超过50ms的任务
            console.warn('检测到长任务:', entry.duration + 'ms', entry)
          }
        })
      })
      observer.observe({ entryTypes: ['longtask'] })
    }
  }

  // 内存使用监控
  observeMemory() {
    if ('memory' in performance) {
      setInterval(() => {
        const memory = performance.memory
        this.metrics.memory = {
          used: Math.round(memory.usedJSHeapSize / 1048576 * 100) / 100 + ' MB',
          total: Math.round(memory.totalJSHeapSize / 1048576 * 100) / 100 + ' MB',
          limit: Math.round(memory.jsHeapSizeLimit / 1048576 * 100) / 100 + ' MB'
        }
      }, 10000) // 每10秒检查一次
    }
  }

  // 获取首次绘制时间
  getFirstPaint() {
    if ('PerformanceObserver' in window) {
      return new Promise((resolve) => {
        const observer = new PerformanceObserver((list) => {
          const entries = list.getEntries()
          if (entries.length > 0) {
            resolve(entries[0].startTime)
            observer.disconnect()
          }
        })
        observer.observe({ entryTypes: ['paint'] })
      })
    }
    return null
  }

  // 获取首次内容绘制时间
  getFirstContentfulPaint() {
    if ('PerformanceObserver' in window) {
      return new Promise((resolve) => {
        const observer = new PerformanceObserver((list) => {
          const entries = list.getEntries()
          if (entries.length > 0) {
            resolve(entries[0].startTime)
            observer.disconnect()
          }
        })
        observer.observe({ entryTypes: ['paint'] })
      })
    }
    return null
  }

  // 获取性能报告
  getReport() {
    return this.metrics
  }
}

// 图片懒加载
export class ImageLazyLoader {
  constructor(options = {}) {
    this.options = {
      threshold: 0.1,
      rootMargin: '50px',
      ...options
    }
    this.images = []
    this.observer = null
    this.init()
  }

  init() {
    if ('IntersectionObserver' in window) {
      this.observer = new IntersectionObserver(this.handleIntersection.bind(this), this.options)
    }
  }

  // 添加图片到懒加载队列
  addImage(img) {
    if (this.observer) {
      this.observer.observe(img)
    } else {
      this.loadImage(img)
    }
  }

  // 处理交叉观察
  handleIntersection(entries) {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        this.loadImage(entry.target)
        this.observer.unobserve(entry.target)
      }
    })
  }

  // 加载图片
  loadImage(img) {
    if (img.dataset.src) {
      img.src = img.dataset.src
      img.classList.remove('lazy')
      img.classList.add('loaded')
    }
  }

  // 销毁观察器
  destroy() {
    if (this.observer) {
      this.observer.disconnect()
    }
  }
}

// 防抖函数
export function debounce(func, wait, immediate = false) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      timeout = null
      if (!immediate) func(...args)
    }
    const callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func(...args)
  }
}

// 节流函数
export function throttle(func, limit) {
  let inThrottle
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

// 预加载资源
export function preloadResource(href, as = 'script') {
  const link = document.createElement('link')
  link.rel = 'preload'
  link.href = href
  link.as = as
  document.head.appendChild(link)
}

// 预获取资源
export function prefetchResource(href) {
  const link = document.createElement('link')
  link.rel = 'prefetch'
  link.href = href
  document.head.appendChild(link)
}

// 创建性能监控实例
export const performanceMonitor = new PerformanceMonitor()

// 创建图片懒加载实例
export const imageLazyLoader = new ImageLazyLoader()
